/* 
 * Copyright TLR Team, Inc. All Rights Reserved.
 */

/* global AMap, self, require, g_assessment, WeixinJSBridge, wx */

TLR.controllers.controller("DevicesViewCtrl", function ($scope) {
    $scope.deviceTypes = [
        {name: "空气测量仪", iconclass: "tlr-icon-airbox trl-airbox-offset", href: "air-measure"},
        {name: "空气净化器", iconclass: "tlr-icon2-car", href: "air-purifier"},
        {name: "行为记录仪", iconclass: "tlr-icon2-eban", href: "eban-recorder"}
    ];
    $scope.onNavClick = function (idx) {
        $scope.selectIdx = idx;
    };
})
.controller("DevicesAirPurifierBindCtrl", function ($rootScope, $scope, $location, DeviceSrv, AirPurifier, UserSrv) {
    var editBindMode = ($location.path().indexOf("/air-purifier-bind-edit") >= 0);
    $scope.airp = editBindMode && $rootScope.currentAirPurifier ? $rootScope.currentAirPurifier : {};
    $scope.scanQRCode = function () {
        try {
            TLR.scanQRCode(UserSrv, $location.absUrl().split("#")[0], function (resultStr) {
                $scope.$apply(function () {
                    $scope.airp.deviceMac = resultStr;
                });
            });
        } catch (err) {
            alert("Exception:" + err);
        }
    };
    $scope.onGetBindIfExist = function (mac) {
        DeviceSrv.get_bind({mac: mac}, function (res) {
            if (res.code === 0 && res.data) {
                $scope.airp = {deviceMac: res.data.devicemac, nickname: res.data.bindnickname};
            } else if (res.code !== 0) {
                alert(res.message);
            } else {
                $scope.airp = {deviceMac: $scope.airp.deviceMac};
            }
        });
    };
    $scope.airPurifierDelDeviceBind = function () {
        DeviceSrv.del_bind({device_id: $scope.airp.deviceMac}, function (res) {
            if (res.code === 0) {
                alert("删除成功");
                $rootScope.currentAirMeasure = null;
                $location.path('/air-purifier');
            } else {
                alert(res.message);
            }
        });
    };
    $scope.airPurifierDeviceBind = function () {
        if ($scope.airp.deviceMac === null || $scope.airp.deviceMac === ""
        || $scope.airp.nickname === null || $scope.airp.nickname === "") {
            alert("必填项不能为空");
        } else {
            if (editBindMode) {
                AirPurifier.edit_bind($scope.airp, function (res) {
                    if (res.code === 0) {
                        alert("修改成功");
                        $location.path('/air-purifier');
                    } else {
                        alert(res.message);
                    }
                });
            } else {
                AirPurifier.add_bind($scope.airp, function (res) {
                    if (res.code === 0) {
                        alert("绑定成功");
                        $location.path('/air-purifier');
                    } else {
                        alert(res.message);
                    }
                });
            }
        }
        console.log($scope.airp);
    };
    $scope.updateDevicePosition = function (mac) {
        var r = confirm("请确保您的位置在设备旁边, 否则定位会产生偏差!");
        if (r === true) {
            TLR.getLocation(UserSrv, $location.absUrl().split("#")[0], function (resLocation) {
                resLocation.devicemac = mac;
                AirPurifier.update_position(resLocation, function (ret) {
                    if (ret.code === 0) {
                        alert("更新设备位置成功");
                    } else {
                        alert("更新位置信息错误,请联系管理员");
                    }
                }, function (error) {
                    alert(error);
                });
            });
        }
    };
})
.controller("DevicesAirMeasureBindCtrl", function ($rootScope, $scope, $location, DeviceSrv, AirDeviceSrv, UserSrv) {
    var editBindMode = ($location.path().indexOf("/air-measure-bind-edit") >= 0);
    $scope.airm = editBindMode && $rootScope.currentAirMeasure ? $rootScope.currentAirMeasure : {};
    $scope.scanQRCode = function () {
        try {
            TLR.scanQRCode(UserSrv, $location.absUrl().split("#")[0], function (resultStr) {
                $scope.$apply(function () {
                    $scope.airm.deviceMac = resultStr;
                });
            });
        } catch (err) {
            alert("Exception:" + err);
        }
    };
    $scope.onGetBindIfExist = function (mac) {
        DeviceSrv.get_bind({mac: mac}, function (res) {
            if (res.code === 0 && res.data) {
                $scope.airm = {deviceMac: res.data.devicemac, nickname: res.data.bindnickname};
            } else if (res.code !== 0) {
                alert(res.message);
            } else {
                $scope.airm = {deviceMac: $scope.airm.deviceMac};
            }
        });
    };
    $scope.airMeasureDelDeviceBind = function () {
        DeviceSrv.del_bind({device_id: $scope.airm.deviceMac}, function (res) {
            if (res.code === 0) {
                alert("删除成功");
                $rootScope.currentAirMeasure = null;
                $location.path('/air-measure');
            } else {
                alert(res.message);
            }
        });
    };
    $scope.airMeasureDeviceBind = function () {
        if ($scope.airm.deviceMac === null || $scope.airm.deviceMac === ""
        || $scope.airm.nickname === null || $scope.airm.nickname === "") {
            alert("必填项不能为空");
        } else {
            if (editBindMode) {
                AirDeviceSrv.edit_bind($scope.airm, function (res) {
                    if (res.code === 0) {
                        alert("修改成功");
                        $location.path('/air-measure');
                    } else {
                        alert(res.message);
                    }
                });
            } else {
                AirDeviceSrv.add_bind($scope.airm, function (res) {
                    if (res.code === 0) {
                        alert("绑定成功");
                        $location.path('/air-measure');
                    } else {
                        alert(res.message);
                    }
                });
            }
        }
        console.log($scope.airm);
    };

    $scope.updateDevicePosition = function (mac) {
        var r = confirm("请确保您的位置在设备旁边, 否则定位会产生偏差!");
        if (r === true) {
            TLR.getLocation(UserSrv, $location.absUrl().split("#")[0], function (resLocation) {
                resLocation.devicemac = mac;
                AirDeviceSrv.update_position(resLocation, function (ret) {
                    if (ret.code === 0) {
                        alert("更新设备位置成功");
                    } else {
                        alert("更新位置信息错误,请联系管理员");
                    }
                }, function (error) {
                    alert(error);
                });
            });
        }
    };
})
.controller("EbanBindListCtrl", function ($scope) {
    $scope.ebanList = [{name: "王绍锋", deviceMac: "100100733"}, {name: "王绍锋1", deviceMac: "100100731"}];
})
.controller("EbanBindCtrl", function ($rootScope, $scope, $location, EBanDeviceSrv, DeviceSrv, UserSrv) {
    console.log("eban", $scope.eban);
    console.log($location.path());
    var editBindMode = ($location.path().indexOf("/eban-bind-edit") >= 0);
    $scope.eban = editBindMode && $rootScope.currentEban ? $rootScope.currentEban : {sex: 0};
    $scope.relation = {};
    $scope.isValidEbanBindInfo = true;
    if (editBindMode) {
        EBanDeviceSrv.alert_relations({code: $scope.eban.deviceMac}, function (res) {
            if (res.code === 0) {
                $scope.relations = res.data;
            } else {
                $scope.relations = undefined;
                alert(res.message);
            }
        });
    }
    $scope.scanQRCode = function () {
        try {
            TLR.scanQRCode(UserSrv, $location.absUrl().split("#")[0], function (resultStr) {
                $scope.$apply(function () {
                    $scope.eban.deviceMac = resultStr;
                });
                $scope.onGetBindIfExist(resultStr);
            });
        } catch (err) {
            alert("Exception:" + err);
        }
    };
    $scope.onGetBindIfExist = function (mac) {
        EBanDeviceSrv.get_exist_health_user({code: mac}, function (res) {
            if (res.code === 0 && res.data) {
                $scope.eban = res.data;
            } else if (res.code !== 0) {
                alert(res.message);
            } else {
                $scope.eban = {deviceMac: $scope.eban.deviceMac};
            }
        });
    };
    $scope.onAddRelationUser = function () {
        $scope.relation.code = $scope.eban.deviceMac;
        EBanDeviceSrv.add_relation($scope.relation, function (res) {
            $scope.relation = {};
            if (res.code === 0) {
                EBanDeviceSrv.alert_relations({code: $scope.eban.deviceMac}, function (res) {
                    if (res.code === 0) {
                        $scope.relations = res.data;
                    } else {
                        $scope.relations = undefined;
                        alert(res.message);
                    }
                });
            } else {
                alert(res.message);
            }
        });
    };
    $scope.onCheckAge = function (dob) {
        if (!dob || dob === "") {
            $scope.isValidEbanBindInfo = false;
            alert("请输入正确的年龄");
        } else {
            $scope.isValidEbanBindInfo = true;
        }
    };
    $scope.onCheckTel = function (tel) {
        if (!tel || !tel.match(/^[0-9\.]*$/)) {
            $scope.isValidEbanBindInfo = false;
            alert("请输入正确的电话");
        } else {
            $scope.isValidEbanBindInfo = true;
        }
    };
    $scope.onCheckHeight = function (height) {
        if (!height || !height.match(/^[0-9\.]*$/)) {
            $scope.isValidEbanBindInfo = false;
            alert("请输入正确的身高");
        } else {
            $scope.isValidEbanBindInfo = true;
        }
    };
    $scope.onCheckWeight = function (weight) {
        if (!weight || !weight.match(/^[0-9\.]*$/)) {
            $scope.isValidEbanBindInfo = false;
            alert("请输入正确的体重");
        } else {
            $scope.isValidEbanBindInfo = true;
        }
    };
    $scope.ebanDelDeviceBind = function () {
        DeviceSrv.del_bind({device_id: $scope.eban.deviceMac}, function (res) {
            if (res.code === 0) {
                alert("删除成功");
                $rootScope.currentEban = null;
                $location.path('/eban-recorder');
            } else {
                alert(res.message);
            }
        });
    };
    $scope.ebanDeviceBind = function () {
        if ($scope.isValidEbanBindInfo) {
            if (!$scope.eban.deviceMac || $scope.eban.deviceMac === ""
            || !$scope.eban.name || $scope.eban.name === ""
            || !$scope.eban.nickname || $scope.eban.nickname === ""
            || !$scope.eban.address || $scope.eban.address === ""
            || !$.isNumeric($scope.eban.height) || !$.isNumeric($scope.eban.weight)
            || !$scope.eban.dob || $scope.eban.dob === "") {
                $scope.isValidEbanBindInfo = false;
                alert("必填项不能为空");
                return;
            }
            if (!$scope.eban.dob.match(/^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/)) {
                $scope.isValidEbanBindInfo = false;
                alert("日期格式不正确");
                return;
            }
        }
        if ($scope.isValidEbanBindInfo) {
            if (editBindMode) {
                EBanDeviceSrv.edit_bind($scope.eban, function (res) {
                    if (res.code === 0) {
                        alert("修改成功");
                        $location.path('/eban-recorder');
                    } else {
                        alert(res.message);
                    }
                });
            } else {
                EBanDeviceSrv.add_bind($scope.eban, function (res) {
                    if (res.code === 0) {
                        alert("绑定成功");
                        $location.path('/eban-recorder');
                    } else {
                        alert(res.message);
                    }
                });
            }
        }
    };
})
.controller("EbanRecorderViewCtrl", function ($rootScope, $scope, $location, EBanDeviceSrv) {
    $scope.onLongPress = function (e) {
        var index = e.originalEvent.long_press_index;
        EBanDeviceSrv.get_bind({code: $scope.healthDevices[index].device_id}, function (res) {
            if (res.code === 0 && res.data) {
                $rootScope.currentEban = res.data;
            } else if (res.code !== 0) {
                alert(res.message);
            }
            $location.path('/eban-bind-edit');
        });
    };
    EBanDeviceSrv.binded(function (response) {
        if (response.code !== 0) {
            alert(response.message);
            return;
        }
        $scope.healthDevices = response.data;
    });
    $scope.deviceClick = function (index) {
        $scope.healthDeviceIndex = index;
        var menu = $("#health-device-menu-id-" + index);
        if (menu.is(":hidden"))
            menu.slideDown({duration: 200});
        else
            menu.slideUp({duration: 200});
    };
})
.controller("EbanCurrentDayDetailViewCtrl", function ($scope, $routeParams, EBanDeviceSrv, EBanDeviceDetailSrv) {
    EBanDeviceSrv.last_basic_data({device_id: $routeParams.storage_id}, function (response) {
        $scope.lastPoint = response.point_data;
        $scope.lastPosition = response.position_data;
    });
    EBanDeviceSrv.last_stat_data({device_id: $routeParams.storage_id}, function (response) {
        $scope.dayStatTimes = response.times;
        var data = [];
        for (var i = 0; i < $scope.dayStatTimes.length; ++i) {
            var time = $scope.dayStatTimes[i];
            data.push({id: i, content: time.content, action: time.action, start: time.start, end: time.end, editable: false});
        }
        var item = data[data.length - 1];
        if (item) {
            $scope.currentDetailData = data;
            $scope.currentContent = item.content;
            $scope.currentTime = item.start.substring(item.start.indexOf(" ")) + (item.end ? ('~' + item.end.substring(item.end.indexOf(" "))) : "");
            EBanDeviceDetailSrv.create("id-eban-current-detail", $scope.onSelect, true, 245, data);
        } else {
            $scope.currentDetailData = null;
            $scope.currentContent = "暂无数据";
        }
    });
    $scope.onSelect = function (item) {
        $scope.$apply(function () {
            if (item && item.content) {
                $scope.currentContent = item.action;
                $scope.currentTime = item.start.substring(item.start.indexOf(" ")) + (item.end ? ('~' + item.end.substring(item.end.indexOf(" "))) : "");
            }
        });
        //console.log("selected: ", item);
    };
})
.controller("EbanDetailHistoryViewCtrl", function ($scope, $routeParams, EBanDeviceSrv, EBanDeviceDetailSrv) {
    $scope.$on(TLR.event.EBAN_HISTORY, function () {
        //console.log("selected: ", $scope.ebanReportType.option)
        EBanDeviceSrv.day_detail_stat({
            device_id: $routeParams.storage_id, date: $scope.ebanReportType.option
        }, function (response) {
            $scope.dayPoint = response.point;
            $scope.dayStatTimes = response.times;
            $scope.dayMessage = response.message ? response.message.split("#") : ["暂无规律"];
            var data = [];
            for (var i = 0; i < $scope.dayStatTimes.length; ++i) {
                var time = $scope.dayStatTimes[i];
                data.push({id: i, content: time.content, action: time.action, start: time.start, end: time.end, editable: false});
            }
            EBanDeviceDetailSrv.create("id-eban-history", $scope.onSelect, false, 125, data);
        });
    });
    $scope.$broadcast(TLR.event.EBAN_HISTORY);
})
.controller("EbanDayReportViewCtrl", function ($scope, $routeParams, EBanDeviceSrv) {
    EBanDeviceSrv.day_stat({
        device_id: $routeParams.storage_id
    }, function (response) {
        $scope.dayStat = response.message;
        $scope.dayStatTotalHour = Math.round($scope.dayStat.total_activity[0] / 60.0 * 100) / 100;
        $scope.dayStepCount = $scope.dayStat.step_count[0];
        $scope.dayActivityCount = $scope.dayStat.liveness[0];
        $scope.daySitCount = $scope.dayStat.static_count[0];
        $scope.dayContent = response.content.daycontent;
    });
})
.controller("EbanWeekReportViewCtrl", function ($scope, $routeParams, EBanDeviceSrv, EbanReportSrv) {
    $scope.onSelect = function (item) {
        $scope.$apply(function () {
            if (item && item.content) {
                $scope.currentContent = item.content;
                $scope.currentTime = item.start.substring(item.start.indexOf(" ")) + (item.end ? ('~' + item.end.substring(item.end.indexOf(" "))) : "");
            }
        });
    };
    require.config({
        paths: {
            echarts: 'libs/echarts/dist'
        }
    });
    require([
        'echarts',
        'echarts/chart/line', // 按需加载所需图表，如需动态类型切换功能，别忘了同时加载相应图表
        'echarts/chart/bar'
    ], function (ec) {
        EBanDeviceSrv.week_stat({
            device_id: $routeParams.storage_id
        }, function (response) {
            var message = response.message;
            var point = [], step = [];
            for (var i = 0; i < message.length; ++i) {
                point.push(message[i].point);
                step.push(message[i].step_count);
            }
            EbanReportSrv.weekReport("id-week-report", ec, "line", "作息趋势", "评分", point);
            EbanReportSrv.weekReport("id-week-report2", ec, "bar", "活动趋势", "步数", step);
        });
    });
})
.controller("EbanStatisticViewCtrl", function ($scope, EBanDeviceSrv) {
    $scope.ebanReportType = {option: '1'};
    $scope.onEbanReportChange = function () {
        $scope.$broadcast(TLR.event.EBAN_HISTORY);
    };
    EBanDeviceSrv.stat_type(function (response) {
        $scope.statTypes = response.stat_type;
    });
})
.controller("DevicesAirMeasureViewCtrl", function ($rootScope, $scope, $location, AIR, AirDeviceSrv, UserSrv) {
    $scope.onLongPress = function (e) {
        $scope.$apply(function () {
            var index = e.originalEvent.long_press_index;
            $rootScope.currentAirMeasure = {deviceMac: $scope.airDevices[index].device_mac, nickname: $scope.airDevices[index].nick_name};
            $location.path('/air-measure-bind-edit');
        });
    };
    $scope.airDeviceListTimer = setInterval(function () {
        // 1mins
        $scope.$broadcast(AIR.event.list);
    }, 1 * 1000 * 60);
    $scope.$on('$destroy', function () {
        // clear timer
        clearInterval($scope.airDeviceListTimer);
    });

    $scope.$on(AIR.event.list, function () {
        AirDeviceSrv.last_bind_data(function (deviceResponse) {
            if (deviceResponse.code !== 0) {
                alert(deviceResponse.message);
                return;
            }
            $scope.airDevices = deviceResponse.data;
        });
    });
    $scope.deviceClick = function (mac, index) {
        $rootScope.currentMac = mac;
        $rootScope.airDeviceIndex = index;
        var menu = $("#air-device-menu-id-" + index);
        if (menu.is(":hidden"))
            menu.slideDown({duration: 300});
        else
            menu.slideUp({duration: 300});
    };
    $scope.onConfigWiFi = function () {
        $('#wifiModal').modal();
    };
    $scope.configWiFi = function () {
        try {
            UserSrv.sign({
                url: $location.absUrl().split("#")[0]
            }, function (res) {
                if (res.code === 0) {
                    var sign = res.data;
                    wx.config({
                        debug: false,
                        appId: sign.appId,
                        timestamp: sign.timestamp,
                        nonceStr: sign.nonceStr,
                        signature: sign.signature,
                        jsApiList: [
                            "configWXDeviceWiFi"
                        ]});
                    WeixinJSBridge.invoke('configWXDeviceWiFi', {}, function (res) {
                        if (res.err_msg === "configWXDeviceWiFi:ok") {
                            alert("连接成功！");
                        } else {
                            alert("连接不成功，请重新尝试！");
                        }
                    });
                } else {
                    alert(res.message);
                }
            });
        } catch (err) {
            alert("Exception:" + err);
        }
    };
    $scope.$broadcast(AIR.event.list);
})
.controller("AirMeasureHistoryViewCtrl", function ($scope, $routeParams, AirDeviceSrv, AirDeviceChart) {
    if ($routeParams.action === "day_history") {
        $scope.airMeasureHistoryLabel = "30天历史";
        AirDeviceSrv.day_history({
            mac: $routeParams.mac,
            data_type: $routeParams.data_type
        }, function (resp) {
            //console.log(dayHistoryResp)
            if (resp.code === 0 && resp.data && resp.data.length > 0)
                AirDeviceChart.create(resp.data);
            else {
                if (console)
                    console.log("error:", resp);
                alert("没有数据");
            }
        });
    } else if ($routeParams.action === "hour_history") {
        $scope.airMeasureHistoryLabel = "24小时历史";
        AirDeviceSrv.hour_history({
            mac: $routeParams.mac,
            data_type: $routeParams.data_type
        }, function (resp) {
            if (resp.code === 0 && resp.data && resp.data.length > 0)
                AirDeviceChart.create(resp.data);
            else {
                if (console)
                    console.log("error:", resp);
                alert("没有数据");
            }
        });
    }
})
.controller("DevicesAirPurifierViewCtrl", function ($rootScope, $scope, $location, UserSrv, DeviceSrv, AirPurifier, HIKESrv) {
    $scope.onPurifierCtrl = function (mac, mode, value) {
        console.log("HIKE:", mac, mode, value);
        if (mode === 'wifi') {
            $('#wifiModal').modal();
            return;
        }
        if (mode !== "switch" && $scope.airPurifierCtrl[mac].switchOn === 0) {
            return;
        }
        if (mode === 'switch') {
            var newValue = value === 1 ? 0 : 1;
            HIKESrv.switchinfo({mac: mac, on: newValue}, function (resp) {
                if (resp.code === 0) {
                    $scope.airPurifierCtrl[mac].switchOn = newValue;
                    if (newValue === 0)
                        $scope.airPurifierCtrl[mac] = new PurifierCtrl($scope.airPurifierCtrl[mac].pm25, $scope.airPurifierCtrl[mac].tvoc);
                } else {
                    alert("设备不在线");
                    if (console)
                        console.log(resp);
                }
            });
        } else if (mode === 'mode') {
            var newValue = value === 1 ? 0 : 1;
            HIKESrv.mode({mac: mac, status: newValue}, function (resp) {
                if (resp.code === 0) {
                    $scope.airPurifierCtrl[mac].windSpeed = 0;
                    $scope.airPurifierCtrl[mac].mode = newValue;
                } else {
                    alert("设备不在线");
                    if (console)
                        console.log(resp);
                }
            });
        } else if (mode === 'wind') {
            var newValue = value % 5 + 1;
            HIKESrv.wind({mac: mac, speed: newValue}, function (resp) {
                if (resp.code === 0) {
                    $scope.airPurifierCtrl[mac].windSpeed = newValue;
                    $scope.airPurifierCtrl[mac].mode = 1;
                } else {
                    alert("设备不在线");
                    if (console)
                        console.log(resp);
                }
            });
        } else if (mode === 'ion') {
            var newValue = value === 1 ? 0 : 1;
            HIKESrv.ion({mac: mac, on: newValue}, function (resp) {
                if (resp.code === 0) {
                    $scope.airPurifierCtrl[mac].ionEnabled = newValue;
                } else {
                    alert("设备不在线");
                    if (console)
                        console.log(resp);
                }
            });
        }
    };
    $scope.configWiFi = function () {
        try {
            TLR.configWIFI(UserSrv, $location.absUrl().split("#")[0]);
        } catch (err) {
            alert("Exception:" + err);
        }
    };
    $scope.onLongPress = function (e) {
        $scope.$apply(function () {
            var index = e.originalEvent.long_press_index;
            $rootScope.currentAirPurifier = {deviceMac: $scope.airDevices[index].device_id, nickname: $scope.airDevices[index].nick_name};
            $location.path('/air-purifier-bind-edit');
        });
    };
    $scope.deviceClick = function (mac, index) {
        $rootScope.currentMac = mac;
        $rootScope.airDeviceIndex = index;
        var menu = $("#air-purifier-menu-id-" + index);
        if (menu.is(":hidden"))
            menu.slideDown({duration: 300});
        else
            menu.slideUp({duration: 300});
        HIKESrv.state({mac: mac}, function (resp) {
            if (resp.code === 0) {
                if (resp.data.state)
                    $scope.airPurifierCtrl[resp.data.mac].switchOn = resp.data.state % 2;
                if (resp.data.speed)
                    $scope.airPurifierCtrl[resp.data.mac].windSpeed = resp.data.speed;
                if (resp.data.anion)
                    $scope.airPurifierCtrl[resp.data.mac].ionEnabled = resp.data.anion;
                if (resp.data.modestate)
                    $scope.airPurifierCtrl[resp.data.mac].mode = resp.data.modestate;
            }
            console.log(resp);
        });
    };
    $scope.webSocketInit = function () {
        try {
            $scope.scopeDestroyed = false;
            $scope.webSocket = new WebSocket($scope.webSocketAddress);
            $scope.webSocket.onopen = $scope.onWebSocketOpen;
            $scope.webSocket.onmessage = $scope.onWebSocketMessage;
            $scope.webSocket.onclose = $scope.onWebSocketClose;
            $scope.webSocket.onerror = $scope.onWebSocketError;
        } catch (err) {
            alert("空气净化器服务异常");
        }
        $scope.$on('$destroy', function () {
            $scope.scopeDestroyed = true;
            $scope.webSocket.close();
        });
    };
    $scope.onWebSocketError = function (evt) {
        $scope.onWebSocketClose();
        console.log(evt);
    };
    $scope.onWebSocketOpen = function (evt) {
        var macList = [];
        for (var i in $scope.airDevices) {
            macList.push($scope.airDevices[i].device_id);
        }
        $scope.webSocket.send(JSON.stringify({
            mac_address: macList
        }));
    };
    $scope.onWebSocketClose = function () {
        if (!$scope.scopeDestroyed) {
            setTimeout($scope.webSocketInit, 3000);
            console.log("closed and reconnecting");
        }
    };
    $scope.onWebSocketMessage = function (event) {
        console.log("Websocket:", event);
        try {
            var data = JSON.parse(event.data);
            $scope.$apply(function () {
                if (data.filter1 !== null && data.filter1 !== undefined && data.filter1 === 0) {
                    $scope.airPurifierCtrl[data.mac].percolatorClear = 1;
                } else if (data.filter2 !== null && data.filter2 !== undefined && data.filter2 === 0) {
                    $scope.airPurifierCtrl[data.mac].percolatorClear = 1;
                } else if (data.filter3 !== null && data.filter3 !== undefined && data.filter3 === 0) {
                    $scope.airPurifierCtrl[data.mac].percolatorClear = 1;
                } else if (data.filter4 !== null && data.filter4 !== undefined && data.filter4 === 0) {
                    $scope.airPurifierCtrl[data.mac].percolatorClear = 1;
                }

                if (data.mac && data.pm25 !== null && data.pm25 !== undefined) {
                    $scope.airPurifierCtrl[data.mac].pm25 = data.pm25;
                }
                if (data.mac && data.tvoc !== null && data.tvoc !== undefined) {
                    $scope.airPurifierCtrl[data.mac].tvoc = data.tvoc;
                }
                if (data.mac && data.state !== null && data.state !== undefined) {
                    $scope.airPurifierCtrl[data.mac].switchOn = data.state % 2;
                }
                if (data.mac && data.anion !== null && data.anion !== undefined) {
                    $scope.airPurifierCtrl[data.mac].ionEnabled = data.anion;
                }
                if (data.mac && data.speed !== null && data.speed !== undefined) {
                    // Manual mode, sleepstate will not be reported (that is decided by device)
                    $scope.airPurifierCtrl[data.mac].windSpeed = data.speed;
                    if (data.speed > 0)
                        $scope.airPurifierCtrl[data.mac].mode = 1;
                }
                if (data.mac && (data.sleepstate !== null && data.sleepstate !== undefined)) {
                    // Sleep or Mode, the speed will not be reported (that is decided by device)
                    $scope.airPurifierCtrl[data.mac].mode = data.sleepstate;
                    $scope.airPurifierCtrl[data.mac].windSpeed = 0;
                }
            });
        } catch (err) {
            alert("服务器推送消息无效");
        }
    };
    // Create a scoket long connection to get the server pushed message
    AirPurifier.binded(function (resp) {
        if (resp.code === 0) {
            $scope.airDevices = resp.data;
            HIKESrv.service_address(function (resp) {
                if (resp.code !== 0) {
                    alert("不能获取空气净化器服务信息");
                    return;
                }
                $scope.webSocketAddress = resp.data;
                $scope.webSocketInit();
            });
            $scope.airPurifierCtrl = {};
            for (var i in $scope.airDevices) {
                var device = $scope.airDevices[i];
                $scope.airPurifierCtrl[device.device_id] = new PurifierCtrl(0, 0.0);
                HIKESrv.data({mac: device.device_id}, function (resp) {
                    if (resp.code === 0) {
                        if (resp.data.pm25)
                            $scope.airPurifierCtrl[resp.data.mac].pm25 = resp.data.pm25;
                        if (resp.data.tvoc)
                            $scope.airPurifierCtrl[resp.data.mac].tvoc = resp.data.tvoc;
                        $scope.airPurifierCtrl[resp.data.mac].percolatorClear = 0;
                        if (resp.data.filter1 !== null && resp.data.filter1 !== undefined && resp.data.filter1 === 0) {
                            $scope.airPurifierCtrl[resp.data.mac].percolatorClear = 1;
                        } else if (resp.data.filter2 !== null && resp.data.filter2 !== undefined && resp.data.filter2 === 0) {
                            $scope.airPurifierCtrl[resp.data.mac].percolatorClear = 1;
                        } else if (resp.data.filter3 !== null && resp.data.filter3 !== undefined && resp.data.filter3 === 0) {
                            $scope.airPurifierCtrl[resp.data.mac].percolatorClear = 1;
                        } else if (resp.data.filter4 !== null && resp.data.filter4 !== undefined && resp.data.filter4 === 0) {
                            $scope.airPurifierCtrl[resp.data.mac].percolatorClear = 1;
                        }
                    }
                });
            }
        } else {
            alert(resp.message);
        }
    });
})
.controller("DevicesAirFilterViewCtrl", function ($scope, HIKESrv, $routeParams) {
    $scope.getAirPercolatorUsageColor = function (value) {
        if (value > 30) {
            return "#A4C167";
        }
        return "#F48484";
    };
    HIKESrv.data({mac: $routeParams.mac}, function (resp) {
        console.log(resp);
        if (resp.code === 0) {
            $scope.airPercolators = [{
                    name: "第一层滤网",
                    value: resp.data.filter1
                }, {
                    name: "第二层滤网",
                    value: resp.data.filter2
                }, {
                    name: "第三层滤网",
                    value: resp.data.filter3
                }, {
                    name: "第四层滤网",
                    value: resp.data.filter4
                }];
        } else {
            $scope.airPercolators = [{
                    name: "第一层滤网",
                    value: 0
                }, {
                    name: "第二层滤网",
                    value: 0
                }, {
                    name: "第三层滤网",
                    value: 0
                }, {
                    name: "第四层滤网",
                    value: 0
                }];
            alert("获取滤网信息失败");
        }
    });
})
.controller("UserCenterListAssessmentCtrl", function ($scope, AssessmentSrv) {
    $scope.assessmentlist = [];
    AssessmentSrv.listassessment({}, function (resp) {
        $scope.assessmentlist = resp;
        console.log("response is:", resp);
        for (var i = 0; i < $scope.assessmentlist.length; i++) {
            console.log($scope.assessmentlist[i].id + " is  " + $scope.assessmentlist[i].pfersonalinformationName);
        }

    }, function (error) {
        console.log("listassessment error with!" + error);
        $scope.assessmentlist = [];
    });
})
.controller("UserCenterViewCtrl", function ($rootScope, $scope, UserSrv) {
    $scope.policyreadstatus = "(未读)";
    UserSrv.get(function (resp) {
        if (resp.code === 0) {
            $scope.user = resp.data;
            $rootScope.userType = $scope.user.type;
            console.log($scope.user);
            if ($scope.user.policyread === 8) {
                $scope.policyreadstatus = "(已读)";
            } else if ($scope.user.policyread > 0) {
                $scope.policyreadstatus = "(已读" + $scope.user.policyread + "/9)";
            }
            console.log("read page:" + $scope.policyreadstatus);
        } else {
            alert(resp.message);
        }
    });
})
.controller("LoginViewCtrl", function ($scope, UserCenterSrv) {
    $scope.userMode = 1;
    $scope.user = {name: "", password: ""};
    $scope.loginClick = function () {
        $scope.userMode = 1;
        console.log($scope.user.name);
        console.log($scope.user.password);
        UserCenterSrv.login($scope.user, function (resp) {
            if (resp.returncode === 0) {
                //console.log("login successfully!");
                self.location = resp.message;
            } else {
                //console.log("user name or password is wrong!");
            }
        }, function (error) {
            //console.log("add error with!" + error)
        });
    };
})
.controller("RegistryViewCtrl", function ($scope, UserSrv) {
    var constLabel = "用户注册";
    var constLabelDoing = "发送注册请求...";
    $scope.user = new UserInfo();
    $scope.registerLabel = constLabel;
    $scope.verifyCodeMsg = "获取";
    $scope.getVerifyCode = $scope.verifyCodeMsg;
    $scope.timerSeconds = 0;
    $scope.registryClick = function () {
        $scope.errorMessage = "";
        if ($scope.backUpMobile !== $scope.user.tel) {
            alert("手机无效,请重新获取验证码");
            return;
        }
        if (!$scope.user.name || $scope.user.name === "" ||
        !$scope.user.tel || $scope.user.tel === "" ||
        !$scope.user.dob || $scope.user.dob === "" ||
        !$scope.user.address || $scope.user.address === "" ||
        !$scope.user.email || $scope.user.email === "") {
            alert("必填项必须合法且不能为空");
            return;
        }
        if (!$scope.user.dob.match(/^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/)) {
            $scope.isValidEbanBindInfo = false;
            alert("日期格式不正确");
        }
        if ($scope.user.mobileCode && $scope.verifyCode && $scope.user.mobileCode === $scope.verifyCode) {
            if (constLabelDoing === $scope.registerLabel) {
                alert("不能重复发起注册，请等待服务器返回。");
                return;
            }
            $scope.registerLabel = constLabelDoing;
            UserSrv.register($scope.user, function (resp) {
                if (resp.code === 0) {
                    self.location = "reg_success.html";
                } else {
                    alert(resp.message);
                }
                $scope.registerLabel = constLabel;
            }, function (error) {
                $scope.registerLabel = constLabel;
                alert(error);
            });
        }
    };
    $scope.sendVerifyCode = function () {
        $scope.backUpMobile = JSCopy($scope.user.tel);
        if ($scope.timerSeconds <= 0) {
            UserSrv.verify_code({mobile: $scope.user.tel}, function (resp) {
                if (resp.code === 0) {
                    $scope.startTimer(60);
                    $scope.verifyCode = resp.data;
                } else {
                    $scope.verifyCode = 0;
                    alert("发送验证码失败, 请查看手机号是否有效");
                }
            });
        }
    };

    $scope.count = function () {
        if (--$scope.timerSeconds <= 0) {
            window.clearInterval($scope.counter);
            $scope.timerSeconds = 0;
            $scope.$apply(function () {
                $scope.getVerifyCode = $scope.verifyCodeMsg;
            });
        } else {
            $scope.$apply(function () {
                $scope.getVerifyCode = $scope.timerSeconds + "秒";
            });
        }
    };
    $scope.startTimer = function (seconds) {
        $scope.timerSeconds = seconds;
        $scope.counter = setInterval($scope.count, 1000);
    };
})
.controller("AssessmentViewCtrl", function ($scope, FileUploader, $location, $routeParams, AssessmentSrv, BodyMapSrv) {
    $scope.assessmentid = $routeParams.id;
    var pageNo = $routeParams.page;
    $scope.pageNo = pageNo ? pageNo : 0;
    // $scope.assessment = g_assessment;
    //not initial or there are difference
    //if(g_assessment == null || (g_assessment.id != $scope.assessmentid && $scope.assessmentid!= null))
    //{
    $scope.assessment = new Assessment();
    $scope.bodymap = {};
    // }
    //console.log("when create assessment:"+$scope.assessment.medication.medicationList.lstdata);
    $scope.assessmentPageUrl = 'app/mvp/template/view/assessment/page-' + $scope.pageNo + '.html';
    $scope.nextPage = function (index) {
        $scope.pageNo = index;
        $location.search("page", index);
        $scope.onSubmit("createassesment", true);
        $scope.assessmentPageUrl = 'app/mvp/template/view/assessment/page-' + index + '.html';
    };

    //upload init
    $scope.uploadurl = 'UploadServlet/' + $scope.assessmentid;
    console.log("upload url:" + $scope.uploadurl);
    $scope.uploadinfo = new uploadinfo();
    var uploader = $scope.uploader = new FileUploader({
        url: $scope.uploadurl
        //formData:[{abvc: 'test'},{'filename2': 'header-value'}]
    });

    //get file list
    if ($scope.pageNo === 16)
    {
        BodyMapSrv.list({assessment: $scope.assessmentid}, function (ret) {
            if (ret.code === 0)
            {
                $scope.bodyMapList = ret.data;
                console.log("get bodymaplist:" + $scope.bodyMapList);
            } else
                console.log("get bodymaplist fail for" + $scope.assessmentid);
        });
    }
    uploader.onProgressItem = function (fileItem, progress) {
        console.info('onProgressItem', fileItem, progress);
    };
    uploader.onCompleteItem = function (fileItem, response, status, headers) {
        console.info('onCompleteItem', fileItem, response, status, headers);
    };
    uploader.onCompleteAll = function () {
        console.info('onCompleteAll');
    };
    //console.log("page 16 is commingfileuploadname");
    $scope.getOldName = function (index)
    {
        if ($scope.uploadinfo.oldnames[index] !== "")
            return $scope.uploadinfo.oldnames[index];
        return $scope.uploader.queue[index].file.name;
    };
    $scope.changeUploadFileName = function ()
    {
        if ($scope.uploader.queue.length > 0)
        {
            $scope.uploadinfo.newnames[$scope.uploader.queue.length - 1] = $scope.uploadinfo.newname;
            $scope.uploadinfo.oldnames[$scope.uploader.queue.length - 1] = $scope.uploader.queue[$scope.uploader.queue.length - 1].file.name;
            //$scope.uploadinfo.newname="";
            //$scope.uploader.formData=[];
            for (var i = 0; i < $scope.uploader.queue.length; i++)
            {
                //var oldname = $scope.uploader.queue[i].file.name;
                //console.log("add old name:"+oldname);
                $scope.uploader.queue[i].fileName = $scope.uploadinfo.newnames[i];
                $scope.uploader.queue[i].file.name = $scope.uploadinfo.newnames[i];
                //console.log("add new2 name:"+$scope.uploadinfo.newnames[i]);
                //$scope.uploader.formData.push({ oldname: $scope.uploadinfo.newnames[i]});
            }
        }
        //console.log("filename2 is:"+$scope.uploadinfo.newname+",index is:"+$scope.uploader.queue.length+",formdata:"+$scope.uploader.formData.length);

    };
    //do not submit when click prev page && (g_assessment == null || (g_assessment.id != $scope.assessmentid))
    $scope.prevPage = function (index) {
        $scope.pageNo = index;
        $location.search("page", index);
        //$scope.onSubmit("createassesment", true);
        $scope.assessmentPageUrl = 'app/mvp/template/view/assessment/page-' + index + '.html';
    };
    //console.log("calling controller:"+$scope.assessmentid);
    if ($scope.assessmentid) {
        //get the detail right now
        if (!g_assessment || (g_assessment.id !== $scope.assessmentid)) {
            var as = new Assessment();
            as.id = $scope.assessmentid;
            AssessmentSrv.get(as, function (resp) {
                //console.log("query successfully");
                if (resp.returncode === 0) {
                    if (!resp.assessment.medication.homeRemedyRecord.allergies_data ||
                    resp.assessment.medication.homeRemedyRecord.allergies_data.length === 0)
                        resp.assessment.medication.homeRemedyRecord.allergies_data = $scope.assessment.medication.homeRemedyRecord.allergies_data;
                    if (!resp.assessment.medication || !resp.assessment.medication.medicationList ||
                    !resp.assessment.medication.medicationList.lstdata || resp.assessment.medication.medicationList.lstdata.length === 0)
                        resp.assessment.medication.medicationList.lstdata = $scope.assessment.medication.medicationList.lstdata;
                    if (!resp.assessment.cover || !resp.assessment.cover.otherPresentPeople ||
                    resp.assessment.cover.otherPresentPeople.length === 0)
                        resp.assessment.cover.otherPresentPeople = $scope.assessment.cover.otherPresentPeople;

                    if (!resp.assessment.personalInformation || !resp.assessment.personalInformation.otherContacts ||
                    resp.assessment.personalInformation.otherContacts.length === 0)
                        resp.assessment.personalInformation.otherContacts = $scope.assessment.personalInformation.otherContacts;

                    if (!resp.assessment.personalInformation || !resp.assessment.personalInformation.professionals ||
                    resp.assessment.personalInformation.professionals.length === 0)
                        resp.assessment.personalInformation.professionals = $scope.assessment.personalInformation.professionals;

                    if (!resp.assessment.medication || !resp.assessment.medication.risk ||
                    !resp.assessment.medication.risk.drugReaction || !resp.assessment.medication.risk.drugReaction.potentialHazard || resp.assessment.medication.risk.drugReaction.potentialHazard.length === 0)
                        resp.assessment.medication.risk.drugReaction.potentialHazard = $scope.assessment.medication.risk.drugReaction.potentialHazard;
                    $scope.assessment = resp.assessment;
                    g_assessment = $scope.assessment;
                    //console.log("get the deail for " + $scope.assessment.id);
                    //console.log("after get assessment:" + $scope.assessment.medication.medicationList.lstdata);
                    if ($scope.assessment.signature.signature && $scope.assessment.signature.signature !== '') {
                        $('#signature1').empty();
                        var i = new Image();
                        i.src = $scope.assessment.signature.signature;
                        $(i).appendTo($('#signature1'));
                    }
                    if ($scope.assessment.signature.assessorSignature && $scope.assessment.signature.assessorSignature !== '') {
                        $('#signature2').empty();
                        var j = new Image();
                        j.src = $scope.assessment.signature.assessorSignature;
                        $(j).appendTo($('#signature2'));
                    }
                    if ($scope.assessment.signature.bodymapSignature && $scope.assessment.signature.bodymapSignature !== '') {
                        $('#signatureBodyMap').empty();
                        var k = new Image();
                        k.src = $scope.assessment.signature.bodymapSignature;
                        $(k).appendTo($('#signatureBodyMap'));
                    }
                } else {
                    alert("读取信息错误,可能是网络问题请重新进入当前页");
                    // console.log("error:" + resp.message);
                }
            }, function (error) {
                alert("读取信息错误,可能是网络问题请重新进入当前页");
                //console.log("add error with!" + error);
                //console.log("error:" + error.message);
            });
        } else {
            $scope.assessment = g_assessment;
            if ($scope.pageNo === 15) {
                setTimeout(function () {
                    if ($scope.assessment.signature.signature && $scope.assessment.signature.signature !== '') {
                        $('#signature1').empty();
                        var i = new Image();
                        i.src = $scope.assessment.signature.signature;
                        $(i).appendTo($('#signature1'));
                    }
                    if ($scope.assessment.signature.assessorSignature && $scope.assessment.signature.assessorSignature !== '') {
                        $('#signature2').empty();
                        var j = new Image();
                        j.src = $scope.assessment.signature.assessorSignature;
                        $(j).appendTo($('#signature2'));
                    }
                }, 2000);
            }
            if ($scope.pageNo === 17) {
                setTimeout(function () {
                    if ($scope.assessment.signature.bodymapSignature && $scope.assessment.signature.bodymapSignature !== '') {
                        $('#signatureBodyMap').empty();
                        var k1 = new Image();
                        k1.src = $scope.assessment.signature.bodymapSignature;
                        $(k1).appendTo($('#signatureBodyMap'));
                    }
                }, 2000);

            }
        }
    }
    $scope.onSubmit = function (action, notReturn) {
        console.log("call submit with " + action);
        g_assessment = $scope.assessment;
        if (action === "createassesment") {
            if (!$scope.assessmentid) {
                AssessmentSrv.add($scope.assessment, function (resp) {
                    if (resp.returncode === 0)
                        $location.search("id", resp.assessment.id);
                    if (resp.returncode === 0 && !notReturn) {
                        self.location = "#/list-assess";
                    }
                    console.log("add successfully!");
                    console.log(resp);
                }, function (error) {
                    console.log("add error with!" + error);
                });
            } else {
                //console.log("medicationlist name 0:"+$scope.assessment.medication.medicationList.lstdata);
                //console.log("medication dose 0:"+$scope.assessment.medication.medicationList.lstdata[0].dose);
                //console.log("medicationlist name 0:"+$scope.assessment.medication.medicationList.lstdata[0].name);
                AssessmentSrv.modify($scope.assessment, function (resp) {
                    if (resp.returncode === 0 && !notReturn) {
                        self.location = "#/list-assess";
                    } else if (resp.returncode !== 0) {
                        alert("保存不成功，请检查数据格式是否正确，或者记录下数据，联系管理员");
                    }
                    console.log("modify successfully!");
                    console.log(resp.message);
                }, function (error) {
                    alert("保存不成功，请重新尝试，或者记录下数据，联系管理员");
                    console.log(error);
                });
            }
        }
    };
    $scope.resetSignature = function () {
        $('#signature1').jSignature('reset');
    };
    $scope.resetAssessorSignature = function () {
        $('#signature2').jSignature('reset');
    };
    $scope.resetBodyMapSignature = function () {
        $('#signatureBodyMap').jSignature('reset');
    };
    $scope.saveSignature = function () {
        $scope.assessment.signature.signature = $('#signature1').jSignature("getData");
        var i = new Image();
        i.src = $scope.assessment.signature.signature;
        $('#signature1').empty();
        $(i).appendTo($('#signature1'));
    };
    $scope.saveAssessorSignature = function () {
        $scope.assessment.signature.assessorSignature = $('#signature2').jSignature("getData");
        var i = new Image();
        i.src = $scope.assessment.signature.assessorSignature;
        $('#signature2').empty();
        $(i).appendTo($('#signature2'));
    };
    $scope.saveBodyMapSignature = function () {
        $scope.assessment.signature.bodymapSignature = $('#signatureBodyMap').jSignature("getData");
        var i = new Image();
        i.src = $scope.assessment.signature.bodymapSignature;
        $('#signatureBodyMap').empty();
        $(i).appendTo($('#signatureBodyMap'));
    };
})
.controller("UserInfoCtrl", function ($scope, UserSrv) {
    UserSrv.get(function (resp) {
        if (resp.code === 0)
            $scope.user = resp.data;
        else
            alert(resp.message);
    });
    $scope.userSave = function () {
        UserSrv.update($scope.user, function (resp) {
            console.log(resp);
            if (resp.code === 0)
                alert("修改成功");
            else
                alert("修改失败");
        });
    };
})
.controller("EmployeeViewRuleCtrl", function ($scope, UserSrv, UserCenterSrv) {
    $scope.userMode = 1;
    $scope.rulePageIndex = 0;
    $scope.employeeRuleTemplUrl = "app/mvp/template/view/user/employee/rules/domiciliary-" + $scope.rulePageIndex + ".html";
    console.log($scope.employeeRuleTemplUrl);
    $scope.user = new UserInfo();
    $scope.finish = function () {
        //change the 
        $scope.policyreadstatus = "(已读)";
        self.location = "#/employee-profile";
    };
    $scope.nextPage = function (index) {
        console.log("next is called with:" + index);
        $scope.rulePageIndex = index;
        $scope.employeeRuleTemplUrl = "app/mvp/template/view/user/employee/rules/domiciliary-" + $scope.rulePageIndex + ".html";
        if (index > $scope.user.policyread) {
            $scope.user.policyread = index;
            UserCenterSrv.updatepolicy($scope.user, function (resp) {
                console.log("call udpate policy3");
                if (resp.returncode === 0) {
                    console.log("updatepolicy successfully!");
                    //self.location = resp.message;
                } else {
                    //console.log("user name or password is wrong!");
                }
            }, function (error) {
                console.log("updatepolicy error with!" + error);
            });
        }
    };
})
.controller("EmployeeViewPositionCtrl", function ($scope, $location, UserSrv, VehicleSrv) {
    var START = "开始定位";
    var STOP = "停止定位";
    $scope.positionUpdateMsg = "准备定位";
    $scope.serviceStatus = {value: '0'};
    VehicleSrv.get_status(function (res) {
        if (res.code === 0)
            $scope.serviceStatus = {value: res.data};
        else
            alert(res.message);
    });
    var h = $(window).height();
    $("#pos-map-container").height(h - 250);
    $scope.trackStatus = START;
    var map_container_id_name = "pos-map-container";
    $scope.posMap = new AMap.Map(map_container_id_name, {
        zoom: 10,
        center: [121.496548, 31.239432],
        animateEnable: false
    });

    $scope.updateLocation = function () {
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                if (res.errMsg === "getLocation:ok") {
                    VehicleSrv.update(res, function (ret) {
                        if (ret.code === 0) {
                            var lng = Number(res.longitude);
                            var lat = Number(res.latitude);
                            $scope.positionUpdateMsg = "更新时间:" + new Date().format("yyyy-MM-dd hh:mm:ss");
                            if (!$scope.driverPosMarker) {
                                var div = document.createElement('div');
                                $(div).css("border-radius", "8px")
                                .css("background-color", "blue")
                                .css("width", "20px")
                                .css("height", "20px");
                                $scope.driverPosMarker = new AMap.Marker({
                                    map: $scope.posMap,
                                    position: [lng, lat],
                                    offset: new AMap.Pixel(-30, -10),
                                    content: div
                                });
                                $scope.posMap.setFitView();
                            } else {
                                $scope.driverPosMarker.setPosition([lng, lat]);
                            }
                            $scope.posMap.setCenter([lng, lat]);
                        } else {
                            alert("更新位置信息错误,请联系管理员");
                        }
                    });
                }
            },
            cancel: function (res) {
                alert('用户拒绝授权获取地理位置');
            }
        });
    };
    $scope.startLocationTask = function () {
        try {
            if ($scope.trackStatus === START) {
                UserSrv.sign({
                    url: $location.absUrl().split("#")[0]
                }, function (res) {
                    if (res.code === 0) {
                        var sign = res.data;
                        wx.config({
                            debug: false,
                            appId: sign.appId,
                            timestamp: sign.timestamp,
                            nonceStr: sign.nonceStr,
                            signature: sign.signature,
                            jsApiList: [
                                "getLocation"
                            ]});
                        $scope.updateLocation();
                        $scope.positionRereshTimer = setInterval(function () {
                            $scope.updateLocation();
                        }, 30 * 1000);// 30s
                        $scope.trackStatus = STOP;
                    }
                });
            } else if ($scope.trackStatus === STOP) {
                if ($scope.positionRereshTimer) {
                    clearInterval($scope.positionRereshTimer);
                    $scope.positionRereshTimer = undefined;
                }
                $scope.trackStatus = START;
            }
        } catch (err) {
            alert("Exception:" + err);
        }
    };
    $scope.setServiceStatus = function () {
        VehicleSrv.set_status({status: $scope.serviceStatus.value}, function (res) {
            if (res.code === 0)
                alert("服务状态设置成功");
            else
                alert(res.message);
        });
        console.log($scope.serviceStatus.value);
    };
});
